package com.shw.loco.adapter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import com.shw.loco.database.DataType;
import com.shw.loco.database.DatabaseHelper;
import com.shw.loco.util.InfoUtils;

/**
 * 
 * @author HAHA
 * 
 */
public class LocoDBThread extends Thread {

	public static final int DB_RECOVER = 0;
	public static final int DB_ADD = 1;
	public static final int DB_RFID = 0;
	public static final int DB_RFINFO = 1;
	public static final int DB_AREA = 2;

	private int oper;
	private Context context;
	private int table;
	private DatabaseHelper databaseHelper;
	private boolean isUI;
	private String dbstr;

	public LocoDBThread(int oper, int table, Context context, String dbstr,
			boolean isUI) {
		this.oper = oper;
		this.context = context;
		this.table = table;
		this.isUI = isUI;
		this.dbstr = dbstr;
		databaseHelper = new DatabaseHelper(context);
	}

	public List<Object[]> readCenterDBInfo() {
		List<Object[]> dblist = new ArrayList<Object[]>();
		String str=dbstr;
		str = str.substring(3 * 2);
		int funCode = Integer.parseInt(str.substring(0, 1 * 2), 16);
		str = str.substring(1 * 2);
		int strLength=Integer.parseInt(str.substring(0, 2*2),16);
		str=str.substring(2*2);
		int dataLength=0;
		switch (funCode) {
		case 6:// 06 调度中心下发区间表的数据
			String lat="";
			String lon="";
			String mile_coor="";
			String area_no="";
			String trace_no="";
			String switch_no="";
			
			String[] areaObj=null;
			try{
				int strLen=(str.length()-4)/94;
			for(int i=0;i<strLen;i++){
				areaObj=new String[7];
				lon=str.substring(0, 2*13);
				str=str.substring(2*13);
				lat=str.substring(0, 2*12);
				str=str.substring(2*12);
				mile_coor=str.substring(0, 2*10);
				str=str.substring(2*10);
				area_no=str.substring(0, 2*4);
				str=str.substring(2*4);
				trace_no=str.substring(0, 2*4);
				str=str.substring(2*4);
				switch_no=str.substring(0, 2*4);
				str=str.substring(2*4);
				areaObj[0]=new String(InfoUtils.HexString2Bytes(lon)).trim();
				areaObj[1]=new String(InfoUtils.HexString2Bytes(lat)).trim();
				areaObj[2]=new String(InfoUtils.HexString2Bytes(mile_coor)).trim();
				areaObj[3]=new String(InfoUtils.HexString2Bytes(area_no)).trim();
				areaObj[4]=new String(InfoUtils.HexString2Bytes(trace_no)).trim();
				areaObj[5]=new String(InfoUtils.HexString2Bytes(switch_no)).trim();
				areaObj[6]=new BigDecimal(areaObj[0]).add(new BigDecimal(areaObj[1])).toString();
				dblist.add(areaObj);
			}}catch(Exception e){
				String rfidstr = "67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"C600";
				try {
					LocoInfoQueue.resultToCenterVector.add(InfoUtils
							.HexToByteArr(rfidstr
									+ InfoUtils.CRC_16(InfoUtils
											.HexToByteArr(rfidstr))));
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			break;
		case 7:// 07调度中心下发RFID表的数据
			String rfid="";
			String rfid_effect="";
			String rfid_track="";
			String rfid_coordinate="";
			String rfid_switchnum="";
			String rfid_crossnum="";
			String rfid_crossdirection="";
			String rfid_relpostion="";
			String rfid_targetpostion="";
			String lats="";
			String lons="";
			String rfid_area="";
			String[] rfidObj=null;
			try{
				int strLens=(str.length()-4)/136;
			for(int i=0;i<strLens;i++){
				rfidObj=new String[13];
				rfid=str.substring(0, 2*24);
				str=str.substring(2*24);
				rfid_effect=str.substring(0, 2*1);
				str=str.substring(2*1);
				rfid_track=str.substring(0, 2*4);
				str=str.substring(2*4);
				rfid_coordinate=str.substring(0, 2*10);
				str=str.substring(2*10);
				rfid_switchnum=str.substring(0, 2*4);
				str=str.substring(2*4);
				rfid_crossnum=str.substring(0, 2*1);
				str=str.substring(2*1);
				rfid_crossdirection=str.substring(0, 2*1);
				str=str.substring(2*1);
				rfid_relpostion=str.substring(0, 2*1);
				str=str.substring(2*1);
				rfid_targetpostion=str.substring(0, 2*4);
				str=str.substring(2*4);
				lons=str.substring(0, 2*13);
				str=str.substring(2*13);
				lats=str.substring(0, 2*12);
				str=str.substring(2*12);
				rfid_area=str.substring(0, 2*4);
				str=str.substring(2*4);
				rfidObj[0]=new String(InfoUtils.HexString2Bytes(rfid)).trim();
				rfidObj[1]=rfid_effect;
				rfidObj[2]=new String(InfoUtils.HexString2Bytes(rfid_track)).trim();
				rfidObj[3]=new String(InfoUtils.HexString2Bytes(rfid_coordinate)).trim();
				rfidObj[4]=new String(InfoUtils.HexString2Bytes(rfid_switchnum)).trim();
				rfidObj[5]=rfid_crossnum;
				rfidObj[6]=rfid_crossdirection;
				rfidObj[7]=rfid_relpostion;
				rfidObj[8]=new String(InfoUtils.HexString2Bytes(rfid_targetpostion)).trim();
				rfidObj[9]=new String(InfoUtils.HexString2Bytes(lons)).trim();
				rfidObj[10]=new String(InfoUtils.HexString2Bytes(lats)).trim();
				rfidObj[11]=new BigDecimal(rfidObj[9]).add(new BigDecimal(rfidObj[10])).toString();
				rfidObj[12]=new String(InfoUtils.HexString2Bytes(rfid_area)).trim();
				dblist.add(rfidObj);
			}}catch(Exception e){
				String rfidstr = "67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"C700";
				try {
					LocoInfoQueue.resultToCenterVector.add(InfoUtils
							.HexToByteArr(rfidstr
									+ InfoUtils.CRC_16(InfoUtils
											.HexToByteArr(rfidstr))));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			break;

		default:
			break;
		}
		
		return dblist;
	}

	public List<Object[]> readDBInfo(int table) {
		List<Object[]> dblist = new ArrayList<Object[]>();
		String pathString = Environment.getExternalStorageDirectory().getPath()
				+ "/SHW/RFIDDB.TXT";
		switch (table) { 
		case 0:
			pathString = Environment.getExternalStorageDirectory().getPath()
					+ "/SHW/RFIDDB.TXT";
			break;
		case 1:
			pathString = Environment.getExternalStorageDirectory().getPath()
					+ "/SHW/RFINFODB.TXT";
			break;
		case 2:
			pathString = Environment.getExternalStorageDirectory().getPath()
					+ "/SHW/AREADB.TXT";
			break;
		default:
			break;
		}

		File file = new File(pathString);
		if (!file.exists()) {
			Looper.prepare();
			Toast.makeText(context, "该文件不存在", Toast.LENGTH_SHORT).show();
			Looper.loop();
		}
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String[] resultLine = null;
			while (br.ready()) {
				resultLine = br.readLine().split(",");
				switch (table) {
				case 0:
					String[] sresultLine = new String[13];
					sresultLine[0]=resultLine[0];
					sresultLine[1]=resultLine[1];
					sresultLine[2]=resultLine[2];
					sresultLine[3]=resultLine[3];
					sresultLine[4]=resultLine[4];
					sresultLine[5]=resultLine[5];
					sresultLine[6]=resultLine[6];
					sresultLine[7]=resultLine[7];
					sresultLine[8]=resultLine[8];
					sresultLine[9]=resultLine[9];
					sresultLine[10]=resultLine[10];
					sresultLine[11]=new BigDecimal(resultLine[9]).add(new BigDecimal(resultLine[10])).toString();
					sresultLine[12]=resultLine[11];;
					dblist.add(sresultLine);
					break;
				case 1:
					
					break;
				case 2:
					String[] resultLines = new String[7];
					resultLines[0]=resultLine[0];
					resultLines[1]=resultLine[1];
					resultLines[2]=resultLine[2];
					resultLines[3]=resultLine[3];
					resultLines[4]=resultLine[4];
					resultLines[5]=resultLine[5];
					resultLines[6]=new BigDecimal(resultLine[0]).add(new BigDecimal(resultLine[1])).toString();
					dblist.add(resultLines);
					break;
				default:
					break;
				}
				
			}
		} catch (FileNotFoundException e) {
			Looper.prepare();
			Toast.makeText(context, "该文件不存在", Toast.LENGTH_SHORT).show();
			Looper.loop();
			e.printStackTrace();
		} catch (IOException e) {
			Looper.prepare();
			Toast.makeText(context, "内容格式有误", Toast.LENGTH_SHORT).show();
			Looper.loop();
			e.printStackTrace();
		}

		return dblist;
	}

	

	@Override
	public void run() {
		List<Object[]> list = null;

		super.run();
		// List<Object[]> list = new ArrayList<Object[]>();
		// Object[] object = { "1", "1", "1", "1", "1", "1", "1" };
		// list.add(object);
		String sql = "";
		if (isUI) {
			list = readDBInfo(table);
			try {
				switch (oper) {
				case DB_RECOVER:
					switch (table) {
					case 0:
						databaseHelper.delete(DataType.RFID);
						sql = "insert into RFID ( rfid, rfid_effect, rfid_track, rfid_coordinate, rfid_switchnum , rfid_crossnum,rfid_crossdirection,rfid_relpostion,rfid_targetpostion,lon,lat,latlon,areano) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
						databaseHelper.insertAllData(sql, list);
						break;
					case 1:
						databaseHelper.delete(DataType.COORDINATE);
						sql = "insert into COORDINATE( equ_name, equ_type, equ_track, equ_coordinate1, equ_coordinate2,equ_coordinate3) values(?,?,?,?,?,?)";
						databaseHelper.insertAllData(sql, list);
						break;
					case 2:
						databaseHelper.delete(DataType.AREA);
						sql = "insert into AREA( lon, lat, mile_coor, areano, track,switch,latlon) values(?,?,?,?,?,?,?)";
						databaseHelper.insertAllData(sql, list);
						break;
					default:
						break;
					}
					break;
				case DB_ADD:
					switch (table) {
					case 0:
						sql = "insert into RFID ( rfid, rfid_effect, rfid_track, rfid_coordinate, rfid_switchnum , rfid_crossnum,rfid_crossdirection,rfid_relpostion,rfid_targetpostion,lon,lat,latlon,areano) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
						databaseHelper.insertRFIDData(sql, list);
						break;
					case 1:
						sql = "insert into COORDINATE( equ_name, equ_type, equ_track, equ_coordinate1, equ_coordinate2,equ_coordinate3) values(?,?,?,?,?,?)";
						databaseHelper.insertAllData(sql, list);
						break;
					case 2:
						sql = "insert into AREA( lon, lat, mile_coor, areano, track,switch,latlon) values(?,?,?,?,?,?,?)";
						databaseHelper.insertAreaData(sql, list);
						break;
					default:
						break;
					}
					break;
				default:
					break;
				}
				Looper.prepare();
				Toast.makeText(context, "成功导入", Toast.LENGTH_SHORT).show();
				Looper.loop();
			} catch (Exception e) {
				Looper.prepare();
				Toast.makeText(context, "数据操作有误: " + e.getMessage(),
						Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		} else {
			try {
				list = readCenterDBInfo();
				switch (table) {
				case 0:
					String rfidstr = "67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"8700";
					try {

						sql = "insert into RFID ( rfid, rfid_effect, rfid_track, rfid_coordinate, rfid_switchnum , rfid_crossnum,rfid_crossdirection,rfid_relpostion,rfid_targetpostion,lon,lat,latlon,areano) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
						databaseHelper.insertRFIDData(sql, list);
						LocoInfoQueue.resultToCenterVector.add(InfoUtils
								.HexToByteArr(rfidstr
										+ InfoUtils.CRC_16(InfoUtils
												.HexToByteArr(rfidstr))));
					} catch (Exception e) {
						rfidstr = "67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"C700";
						LocoInfoQueue.resultToCenterVector.add(InfoUtils
								.HexToByteArr(rfidstr
										+ InfoUtils.CRC_16(InfoUtils
												.HexToByteArr(rfidstr))));
					}
					break;
				case 1:
					sql = "insert into COORDINATE( equ_name, equ_type, equ_track, equ_coordinate1, equ_coordinate2,equ_coordinate3) values(?,?,?,?,?,?)";
					databaseHelper.insertAllData(sql, list);
					break;
				case 2:
					String areastr = "67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"8600";
					try {

						sql = "insert into AREA( lon, lat, mile_coor, areano, track,switch,latlon) values(?,?,?,?,?,?,?)";
						databaseHelper.insertAreaData(sql, list);
						LocoInfoQueue.resultToCenterVector.add(InfoUtils
								.HexToByteArr(areastr
										+ InfoUtils.CRC_16(InfoUtils
												.HexToByteArr(areastr))));
					} catch (Exception e) {
						areastr = "67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"C600";
						LocoInfoQueue.resultToCenterVector.add(InfoUtils
								.HexToByteArr(areastr
										+ InfoUtils.CRC_16(InfoUtils
												.HexToByteArr(areastr))));
					}
					break;
				default:
					break;
				}
			} catch (Exception e) {

			}
		}
	}

}
